package com.androidbegin.jsonparsetutorial;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidbegin.jsonparsetutorial.*;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SingleItemView extends Activity {
	// Declare Variables
	String id;
	String content;
	String img;
	static String IMAGE="src";
	String position;
	ProgressDialog pDialog;
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jidla;
	GridView grdview;
	ViewAdapter adapter;
	JSONObject jsonobject;
	JSONArray jsonarray;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.singleitemview);
		Intent i = getIntent();
		id = "http://rest.playboyviet.com/public/phototamtayvn-rest/"
				+ i.getStringExtra("id");
		grdview=(GridView)findViewById(R.id.grid_view);
		
		new DownloadJSON().execute();
	}
	// DownloadJSON AsyncTask
		private class DownloadJSON extends AsyncTask<Void, Void, Void> {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// Create a progressdialog
				pDialog = new ProgressDialog(SingleItemView.this);
				// Set progressdialog message
				pDialog.setMessage("Loading...");
				pDialog.setIndeterminate(false);
				// Show progressdialog
				
				pDialog.show();
			}

			@Override
			protected Void doInBackground(Void... params) {
				Log.i("doInBackground - id:",id);
				arraylist = new ArrayList<HashMap<String, String>>();
				ServiceHandler sh = new ServiceHandler();
				String jsonStr = sh.makeServiceCall(id, ServiceHandler.GET);
				Log.i("doInBackground - jsonStr:",jsonStr);
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					jsonarray = jsonObj.getJSONArray("data");

					for (int i = 0; i < jsonarray.length(); i++) {
						HashMap<String, String> map = new HashMap<String, String>();
						jsonobject = jsonarray.getJSONObject(i);
						map.put("src", jsonobject.getString("src"));
						arraylist.add(map);
					}
				} catch (JSONException e) {
					Log.e("Error", e.getMessage());
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void args) {
				grdview = (GridView) findViewById(R.id.grid_view);
				Log.i("onPostExecute - ltview:",grdview.toString());
				adapter = new ViewAdapter(SingleItemView.this, arraylist);
				Log.i("onPostExecute - adapter:",adapter.toString());
				grdview.setAdapter(adapter);
				pDialog.dismiss();

			}
		}
}